<template>
    <div style="width: 350px;">
      <el-form ref="ruleFormRef" :model="adminForm" :rules="rules" label-width="120px" class="demo-ruleForm" :size="formSize"
        status-icon>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="adminForm.adminName" />
        </el-form-item>
        <el-form-item label="密码" prop="userPwd">
          <el-input type="password" v-model="adminForm.adminPwd" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            添加
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </template>
      
  <script lang="ts" setup>
  import { reactive, ref } from 'vue'
  import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
  import api from '@/api'
  
  const formSize = ref('default')
  const ruleFormRef = ref<FormInstance>()
  const adminForm = ref({
    adminName: '',
    adminPwd: '',
    roleId: 1
  })
  
  const rules = reactive<FormRules>({
    adminName: [
      {
        required: true,
        message: '用户名不能为空',
        trigger: 'change',
      },
    ],
    adminPwd: [
      {
        required: true,
        message: '密码不能为空',
        trigger: 'change',
      },
    ],
  })
  
  
  const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        api.admin.addAdmin(adminForm.value)
          .then(response => {
            // 在这里可以处理提交成功后的逻辑
            ElNotification({
              title: 'Success',
              message: response.data.msg,
              type: 'success',
              duration: 1500
            })
            formEl.resetFields()
          })
          .catch(error => {
            ElNotification({
              title: 'Error',
              message: error.data.msg,
              type: 'error',
              duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
          });
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  
  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  </script>
      